/**
 * @description address router
 */

const router = require('koa-router')()
const { SuccessModel, ErrorModel } = require('../res-model/index')
const loginCheck = require('../middleware/loginCheck')
const {
    createAddress,
    getAddressList,
    getAddressById,
    updateAddress,
} = require('../controller/address')

router.prefix('/api/user/address')
//创建收货地址

router.post('/', loginCheck, async function (ctx, next) {
    const username = ctx.session.userInfo.username
    const data = ctx.request.body
    //创建数据
    try {
        const newAddress = await createAddress(username, data)
        ctx.body = new SuccessModel(newAddress)
    } catch (ex) {
        console.error(ex)
        ctx.body = new ErrorModel(10004, '创建收货地址失败')
    }
})

//获取收货地址列表

router.get('/', loginCheck, async function (ctx, next) {
    const username = ctx.session.userInfo.username
    //获取列表
    const list =await getAddressList(username)
    // if (list) {
        ctx.body = new SuccessModel(list)
    // } else {
    //     ctx.body = new ErrorModel(10005, '获取地址列表失败')
    // }
})

//获取单个收货地址

router.get('/:id',loginCheck,async function(ctx,next){
    const id=ctx.params.id
    const address=await getAddressById(id)
    ctx.body=new SuccessModel(address)
})

//跟新收货地址

router.patch('/:id',loginCheck,async function(ctx,next) {
    const id=ctx.params.id
    const data=ctx.request.body
    const username=ctx.session.userInfo.username
    //更新
    const newAddress=await updateAddress(id,username,data)
    ctx.body=new SuccessModel(newAddress)
})

module.exports = router